﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms ;

namespace XDesigner.AppFramework.WinForms
{
    public class MdiChildrenManager
    {
        public MdiChildrenManager()
        {
        }

        public MdiChildrenManager(Form parentForm)
        {
            this._MdiParent = parentForm;
        }

        private Form _MdiParent = null;

        public Form MdiParent
        {
            get
            { 
                return _MdiParent;
            }
            set
            {
                _MdiParent = value;
            }
        }

        private void CheckParent()
        {
            if (_MdiParent == null)
            {
                throw new ArgumentNullException("this.MdiParent");
            }
        }
        public Form this[int index]
        {
            get
            {
                CheckParent();
                return _MdiParent.MdiChildren[index];
            }
        }

        public Form this[Type t]
        {
            get
            {
                return FindChildForm(t, false );
            }
        }

        public Form FindChildForm( Type frmType , bool createForm )
        {
            CheckParent();
            foreach (Form frm in this._MdiParent.MdiChildren)
            {
                if (frm.GetType().Equals(frmType))
                {
                    return frm;
                }
            }
            if (createForm)
            {
                Form newForm = (Form)System.Activator.CreateInstance(frmType);
                newForm.MdiParent = _MdiParent ;
                return newForm;
            }
            return null;
        }//FindChildForm

        public void CloseAll()
        {
            CloseAll(null);
        }

        public void CloseAll(Type[] excludeFormType)
        {
            CheckParent();
            Form[] frm = _MdiParent.MdiChildren;
            for (int iCount = frm.Length - 1; iCount >= 0; iCount--)
            {
                Form frm2 = frm[iCount];
                if (excludeFormType != null)
                {
                    foreach (Type t in excludeFormType)
                    {
                        if (t.IsInstanceOfType(frm2))
                        {
                            goto NextForm;
                        }
                    }//foreach
                }
                frm2.Close();
            NextForm: ;
            }//for
        }

    }
}
